﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using ImageProcessingLibrary;
using System.Threading;

namespace BinocularVision
{
    public class FaceDetection: BrainProcess
    {
        #region Fields
        private ImageProcessor leftWebCamOriginalImage;
        private ImageProcessor rightWebCamOriginalImage;
        
        private ImageProcessor leftWebCamProcessedImage;
        private ImageProcessor rightWebCamProcessedImage;
        #endregion

        #region Public methods
        public override void Step()
        {
            if (CurrentState == 0)
            {
                Bitmap leftImage = Robot.Instance.Body.LeftWebCam.ReadingAsBitmap;
                Bitmap rightImage = Robot.Instance.Body.RightWebCam.ReadingAsBitmap;
                if (leftImage != null && rightImage != null)
                {
                    leftWebCamOriginalImage = new ImageProcessor(leftImage);
                    rightWebCamOriginalImage = new ImageProcessor(rightImage);
                    this.CurrentState = 1;
                }
            }
            else if (CurrentState == 1)
            {
                lock (this) // Process both images before unlocking
                {
                    this.leftWebCamOriginalImage.Lock();
                    this.rightWebCamOriginalImage.Lock();

                    this.leftWebCamProcessedImage = leftWebCamOriginalImage.GetSkinPixelsYCbCr();
                    this.rightWebCamProcessedImage = rightWebCamOriginalImage.GetSkinPixelsYCbCr();

                    this.leftWebCamOriginalImage.UnLock();
                    this.rightWebCamOriginalImage.UnLock();
                }
                
                this.CurrentState = 0;
            }
        }
        #endregion

        #region Properties
        public Bitmap LeftWebCamProcessedImage
        {
            get
            {
                if (this.leftWebCamProcessedImage != null)
                {
                    return new Bitmap(leftWebCamProcessedImage.ProcessedBitmap);
                }
                else
                {
                    return new Bitmap(320, 240);
                }
            }
        }

        public Bitmap RightWebCamProcessedImage
        {
           get 
           {
               if (this.rightWebCamProcessedImage != null)
               {
                   return new Bitmap(rightWebCamProcessedImage.ProcessedBitmap);
               }
               else
               {
                   return new Bitmap(320, 240);
               }
           }
        }

        #endregion


    }
}
